#!/usr/bin/python

#
# Simple command line tool for managing WordPress Post
# Author: Juanjo Escribano <juanjo.escribano@gmail.com>
# Version: 0.1 (beta)
# License: GPL v3
# Notes : by the moment it only supports "New Post" operation
#

import xmlrpclib
from datetime import datetime
import getopt
import sys
from wp_config import configFile

class Post:
    """
    This class will save the post info
    Private Attributes : 
        _post_title : the title of the post
        _post_description : the body of the post
        _post_date : date timestamp of the post (now())
        _post_tags : comma separated tags string
    """
    _post_title = ""
    _post_description = ""
    _post_date = ""
    _post_date = ""
    _post_tags = ""

    def __init__(self, post_title, post_description, post_tags):
        """
        class constructor
        """
        self._post_title = post_title
        self._post_description = post_description
        actual_date = datetime.now()
        self._post_date = actual_date.year.__str__() + " " + actual_date.month.__str__() + " " + actual_date.day.__str__()
        self._post_tags = post_tags

    def toStructure(self):
        """
        Creates a structure with the information. The elements of the struct
        are defined as elements of <item> element in RSS 2.0 (by the moment
        I don't support all of them
        """
        post_structure = {
                         "title" : self._post_title,
                         "description" : self._post_description,
                         "pubDate" : self._post_date,
                         }
        categories = self._post_tags.split(",")
        print self._post_tags
        post_structure["categories"] = categories
        return post_structure

def main():
    """
    Main funcion. Parse the parameters and do the job
    """

    user = ""
    passwd = ""
    server = ""
    title = ""
    post = ""
    blog = ""
    tags = ""
    options, args = getopt.getopt(sys.argv[1:], "", ["blog=", "server=", "user=", "pass=", "title=", "post=", "tags="])
    for opt,val in options:
        if opt == "--user":
            user = val
        elif opt == "--pass":
            passwd = val
        elif opt == "--title":
            title = val
        elif opt == "--post":
            if val == "stdin":
                post = sys.stdin.read()
            else:
                post = val
        elif opt == "--server":
            server = val
        elif opt == "--blog":
            blog = val
        elif opt == "--tags":
            tags = val

    # user and server are not optative
    if (server == "" and user == "" and blog == "") or ((server == "" or user == "") and blog == ""):
        print "Syntax: " + sys.argv[0] + " [<--server=wordpress_addr> <--user=username> | <--blog=blogName> ] [--pass=password --title=title --post= [stdin | some_text] --tags=<tag1, tag2...>]"
        sys.exit(0)

    # get the connection parameters
    if blog != "":
        # ok ... then let's have it from config file
        conf = configFile(blog)
        user = conf.getUser()
        passwd = conf.getPass()
        server = conf.getServer()
        if server == "" or user == "":
            print "There was an error reading from Configuration file. Please check it"
            sys.exit(0)

    # init a xmlrpclib.Server object 
    server = xmlrpclib.Server(server + "/xmlrpc.php")
    # Create a Post Object with title and post. Then try to post it
    post = Post(title, post, tags)
    try:
        res = server.metaWeblog.newPost("1", user, passwd, post.toStructure(), "1")
    except xmlrpclib.ProtocolError, err:
        print "Error conecting with server"
        sys.exit(-1)
    except xmlrpclib.Fault, err:
        print "Error :" + err.__str__()
        sys.exit(-1)
    except:
        print "Unknown Error"
        sys.exit(-1)

    print "Post id: " + res

# Start here
if __name__ == "__main__":
    main()

